// src/pages/admin/user/UserList.jsx
import React, { useState, useEffect } from 'react';
import { Table, Input, Button, Card, Spin, Tag, message, Popconfirm, Modal, Select, Space } from 'antd';
import {
  UserOutlined,
  SearchOutlined,
  FilterOutlined,
  MailOutlined
} from '@ant-design/icons';
import axios from 'axios';
import { getAuthToken } from '@/router';

const { Option } = Select;

// Mock data for when API fails
const mockUsers = {
  data: {
    records: [
      {
        id: 1,
        username: '用户1',
        email: 'user1@example.com',
        userLevel: 2,
        shareRatio: 1.5,
        status: 'active'
      },
      {
        id: 2,
        username: '用户2',
        email: 'user2@example.com',
        userLevel: 3,
        shareRatio: 0.8,
        status: 'banned'
      },
      {
        id: 3,
        username: '用户3',
        email: 'user3@example.com',
        userLevel: 1,
        shareRatio: 0.3,
        status: 'inactive'
      },
      {
        id: 4,
        username: '用户4',
        email: 'user4@example.com',
        userLevel: 2,
        shareRatio: 2.1,
        status: 'active'
      },
      {
        id: 5,
        username: '用户5',
        email: 'user5@example.com',
        userLevel: 3,
        shareRatio: 0.4,
        status: 'banned'
      }
    ],
    current: 1,
    size: 10,
    total: 5
  }
};

const statusOptions = [
  { value: 'all', label: '全部状态' },
  { value: 'active', label: '正常' },
  { value: 'banned', label: '已封禁' },
  { value: 'inactive', label: '未激活' }
];

// 搜索类型选项
const searchTypeOptions = [
  { value: 'username', label: '用户名' },
  { value: 'email', label: '邮箱' },
  { value: 'all', label: '用户名或邮箱' }
];

const UserList = () => {
  const [loading, setLoading] = useState(true);
  const [users, setUsers] = useState([]);
  const [searchText, setSearchText] = useState('');
  const [searchType, setSearchType] = useState('all'); // 默认搜索类型：所有字段
  const [statusFilter, setStatusFilter] = useState('all');
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
  const [unbanModalVisible, setUnbanModalVisible] = useState(false);
  const [currentUserId, setCurrentUserId] = useState(null);
  const [reason, setReason] = useState('申诉通过'); // 默认解封原因

  const fetchData = async (page = 1, pageSize = 10, keyword = '', type = 'all', status = 'all') => {
    try {
      setLoading(true);

      // 准备请求参数
      const params = {
        page,
        size: pageSize,
        keyword,
        type, // 添加搜索类型参数
        status: status === 'all' ? null : status
      };

      const response = await axios.get('http://localhost:8080/api/user/list', {
        params,
        headers: { Authorization: getAuthToken() }
      });

      if (response.data.code === 200) {
        setUsers(response.data.data.records);
        setPagination({
          current: response.data.data.current,
          pageSize: response.data.data.size,
          total: response.data.data.total
        });
      } else {
        message.error(response.data.message || '获取数据失败');
      }
    } catch (error) {
      console.error('获取用户列表失败，使用模拟数据:', error);

      // 在模拟数据中实现状态和关键词筛选
      let filteredRecords = mockUsers.data.records;

      // 状态筛选
      if (status !== 'all') {
        filteredRecords = filteredRecords.filter(user => user.status === status);
      }

      // 关键词筛选
      if (keyword) {
        filteredRecords = filteredRecords.filter(user => {
          if (type === 'username') {
            return user.username.includes(keyword);
          } else if (type === 'email') {
            return user.email.includes(keyword);
          } else { // 'all' 搜索所有字段
            return user.username.includes(keyword) || user.email.includes(keyword);
          }
        });
      }

      setUsers(filteredRecords);
      setPagination({
        current: mockUsers.data.current,
        pageSize: mockUsers.data.size,
        total: filteredRecords.length
      });
      message.warn('后端连接失败，使用模拟数据');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData(1, pagination.pageSize, searchText, searchType, statusFilter);
  }, []);

  const handleTableChange = (pagination) => {
    fetchData(pagination.current, pagination.pageSize, searchText, searchType, statusFilter);
  };

  const handleSearch = () => {
    fetchData(1, pagination.pageSize, searchText, searchType, statusFilter);
  };

  const handleSearchTypeChange = (value) => {
    setSearchType(value);
  };

  const handleStatusFilterChange = (value) => {
    setStatusFilter(value);
    fetchData(1, pagination.pageSize, searchText, searchType, value);
  };

  const handleBanUser = async (userId, days) => {
    try {
      await axios.post('http://localhost:8080/api/admin/user/ban', {
        userId,
        reason: '管理员操作',
        banDays: days
      }, {
        headers: { Authorization: getAuthToken() }
      });
      message.success('封禁成功');
      fetchData(pagination.current, pagination.pageSize, searchText, searchType, statusFilter);
    } catch (error) {
      console.error('封禁用户失败:', error);
      message.error('封禁失败');
    }
  };

  const showUnbanModal = (userId) => {
    setCurrentUserId(userId);
    setUnbanModalVisible(true);
  };

  const handleUnbanConfirm = async () => {
    try {
      await axios.post(`http://localhost:8080/api/admin/user/unban/${currentUserId}`, null, {
        params: { reason },
        headers: { Authorization: getAuthToken() }
      });
      message.success('解封成功');
      fetchData(pagination.current, pagination.pageSize, searchText, searchType, statusFilter);
      setUnbanModalVisible(false);
      setReason('申诉通过'); // 重置原因
    } catch (error) {
      console.error('解封用户失败:', error);
      message.error('解封失败');
    }
  };

  const handleUnbanCancel = () => {
    setUnbanModalVisible(false);
    setReason('申诉通过');
  };

  const getSearchPlaceholder = () => {
    switch (searchType) {
      case 'username':
        return '按用户名搜索...';
      case 'email':
        return '按邮箱搜索...';
      default:
        return '按用户名或邮箱搜索...';
    }
  };

  const getSearchIcon = () => {
    switch (searchType) {
      case 'username':
        return <UserOutlined />;
      case 'email':
        return <MailOutlined />;
      default:
        return <SearchOutlined />;
    }
  };

  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      render: text => <span><UserOutlined /> {text}</span>
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email'
    },
    {
      title: '用户等级',
      dataIndex: 'userLevel',
      key: 'userLevel',
      render: level => <Tag color="blue">Lv.{level}</Tag>
    },
    {
      title: '分享率',
      dataIndex: 'shareRatio',
      key: 'shareRatio',
      // 修复点：安全处理shareRatio可能为null/undefined的情况
      render: shareRatio => {
        const num = parseFloat(shareRatio);
        if (isNaN(num)) {
          return <Tag color="gray">N/A</Tag>;
        }
        return <Tag color={num >= 1 ? 'green' : 'red'}>{num.toFixed(2)}</Tag>;
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: status => {
        const statusMap = {
          active: { color: 'green', text: '正常' },
          banned: { color: 'red', text: '已封禁' },
          inactive: { color: 'orange', text: '未激活' }
        };
        const statusInfo = statusMap[status] || { color: 'gray', text: '未知' };
        return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
          <div>
            {record.status === 'banned' ? (
                <Button
                    type="primary"
                    onClick={() => showUnbanModal(record.id)}
                >
                  解封
                </Button>
            ) : (
                <Popconfirm
                    title="选择封禁时长"
                    description={
                      <Space direction="vertical">
                        <div style={{ display: 'flex', gap: '8px', padding: '8px 0', flexWrap: 'wrap' }}>
                          <Button size="small" onClick={() => handleBanUser(record.id, 1)}>1天</Button>
                          <Button size="small" onClick={() => handleBanUser(record.id, 7)}>7天</Button>
                          <Button size="small" onClick={() => handleBanUser(record.id, 30)}>30天</Button>
                          <Button size="small" danger onClick={() => handleBanUser(record.id, 0)}>永久</Button>
                        </div>
                        <span style={{ fontSize: 12, color: '#999' }}>点击所需时长进行封禁</span>
                      </Space>
                    }
                    okText=""
                    cancelText="取消"
                    icon={null}
                >
                  <Button danger>封禁</Button>
                </Popconfirm>
            )}
          </div>
      )
    }
  ];

  return (
      <Card
          title="用户列表"
          bordered={false}
          extra={
            <Space>
              <Select
                  value={searchType}
                  onChange={handleSearchTypeChange}
                  style={{ width: 130 }}
              >
                {searchTypeOptions.map(option => (
                    <Option key={option.value} value={option.value}>{option.label}</Option>
                ))}
              </Select>
              <Input
                  placeholder={getSearchPlaceholder()}
                  value={searchText}
                  onChange={(e) => setSearchText(e.target.value)}
                  style={{ width: 200 }}
                  onPressEnter={handleSearch}
                  prefix={getSearchIcon()}
              />
              <Button
                  type="primary"
                  icon={<SearchOutlined />}
                  onClick={handleSearch}
              >
                搜索
              </Button>
            </Space>
          }
      >
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
          <Select
              value={statusFilter}
              onChange={handleStatusFilterChange}
              style={{ width: 150 }}
              suffixIcon={<FilterOutlined />}
          >
            {statusOptions.map(option => (
                <Option key={option.value} value={option.value}>{option.label}</Option>
            ))}
          </Select>

          <div>
            总计: <Tag color="blue">{pagination.total}</Tag> 个用户
          </div>
        </div>

        <Spin spinning={loading}>
          <Table
              columns={columns}
              dataSource={users}
              rowKey="id"
              pagination={{
                ...pagination,
                showTotal: total => `共 ${total} 条`,
                showSizeChanger: true,
                showQuickJumper: true
              }}
              onChange={handleTableChange}
          />
        </Spin>

        {/* 解封确认模态框 */}
        <Modal
            title="确认解封"
            open={unbanModalVisible}
            onOk={handleUnbanConfirm}
            onCancel={handleUnbanCancel}
            okText="确认解封"
            cancelText="取消"
        >
          <div>
            <p>确定要解封这个用户吗？</p>
            <p>
              <label>解封原因：</label>
              <Input
                  value={reason}
                  onChange={(e) => setReason(e.target.value)}
                  placeholder="请输入解封原因"
              />
            </p>
            <p style={{ fontSize: '12px', color: '#999' }}>
              提示：解封原因将会记录在案
            </p>
          </div>
        </Modal>
      </Card>
  );
};

export default UserList;